package mpYoga

import (
	"duoke/context"
	"duoke/model"
	"duoke/model/yogaModel"
	"duoke/service"
	yogaService "duoke/service/yoga"
	"duoke/utils/gconv"
	"duoke/utils/request"
	"duoke/utils/response"
	"duoke/utils/valid"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
)

var CourseOrder = new(courseOrderCtl)

type courseOrderCtl struct{}

func (ctl *courseOrderCtl) CreateOrder(c *gin.Context) {
	req := request.JsonMap(c)
	fromId := gconv.Int(req["from_id"])
	if fromId == 0 {
		response.Error(c, "参数缺失【from_id】", nil)
		return
	}
	order, err := yogaService.CourseOrder.CreateOrder(c, fromId)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "成功", gin.H{"order_no": order})
}
func (ctl *courseOrderCtl) PayOrder(c *gin.Context) {
	var req yogaModel.PayOrder
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	// 创建订单
	order, err := yogaService.CourseOrder.OrderAmount(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	// 构建支付单
	notifyUrl := context.Global.Domain + "/mp/notify/yoga_course_notify"
	pay, err := service.WechatPay.OrderPay(c, &model.ReqWechatPay{
		NotifyUrl: notifyUrl,
		Openid:    order.Openid,
		OrderNo:   order.OrderNo,
		PayAmount: order.TotalAmount,
		Desc:      order.Body,
		SubMchId:  order.SubMchId,
	})
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "success", pay)
}
func (ctl *courseOrderCtl) MyCourseOrder(c *gin.Context) {
	var req model.ReqListV2
	if err := c.ShouldBind(&req); err != nil {
		response.Error(c, valid.GetError(err.(validator.ValidationErrors), req), nil)
		return
	}
	list, total, err := yogaService.CourseOrder.MyOrder(c, &req)
	if err != nil {
		response.Error(c, err.Error(), nil)
		return
	}
	response.Success(c, "成功", gin.H{"list": list, "total": total})
}
